<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
  <style>
    html,
    body,
    #container {
      width: 100%;
      height: 100%;
    }
  </style>
  <title>高德地图-电子围栏-多边形增删改</title>
  <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
  <!-- 高德地图 -->
  <script type="text/javascript"
    src="https://webapi.amap.com/maps?v=2.0&key=a13f2a0c15e7fc108af3a866c14ee5d8&plugin=AMap.PolygonEditor"></script>
</head>
<body>
  <div id="container"></div>
  <div class="input-card" style="width: 120px;bottom: 150px">
    <button class="btn" onclick="editPolygon()" >编辑图形</button>
  </div>
  <div class="input-card" style="width: 120px">
    <button class="btn" onclick="addPolygon()" style="margin-bottom: 5px">添加图形</button>
    <button class="btn" onclick="submitData(1)" style="margin-bottom: 5px">取消</button>
    <button class="btn" onclick="submitData(2)" style="margin-bottom: 5px">保存</button>
  </div>
  <script type="text/javascript">
    var map  = null;
    var polyEditor = null; //多边形编辑器
    var pathArr = []; //获取后台模拟数据
    var polygonArr = []; //地图上所有的多边形
    var labelArr = [] //地图上所有多边形所对应的名称
    var isEdit = false; //是否处于可编辑状态
 
    initMap(); //初始化地图
    //初始化地图
    function initMap() {
      map = new AMap.Map("container", {
        center: [116.400274, 39.905812],
        zoom: 14
      });
      getInitMapData() //获取初始地图多边形数据
    }
    //获取初始地图多边形数据
    function getInitMapData() {
      var path1 = [[116.475334, 39.997534], [116.476627, 39.998315], [116.478603, 39.99879], [116.478529, 40.000296], [116.475082, 40.000151], [116.473421, 39.998717]]
      var path2 = [[116.474595, 40.001321], [116.473526, 39.999865], [116.476284, 40.000917]]
       pathArr = [
        {
          path: path1,
          mapId: 1,
        }, 
        {
          path: path2,
          mapId: 2,
        }, 
      ]
      showInitPolygon(); //初始展示所有多边形
    }
    //初始展示所有多边形
    function showInitPolygon() {
      var dealPolygonArr = []
      var dealLabelArr = []
      pathArr && pathArr.forEach((el, index) => {
        var polygon = new AMap.Polygon({
          path: el.path,
          fillColor: "#FF8D8D",
          fillOpacity: 0.3,
          strokeWeight: 3,
          strokeColor: "#FF8D8D",
          strokeOpacity: 1,
          zIndex: 1,
          extData: {
            mapId: el.mapId,
          }
        })
        var label = showText(polygon); //每个多边形添加label
        //
        dealPolygonArr.push(polygon)
        polygonArr = dealPolygonArr
        //
        dealLabelArr.push(label)
        labelArr = dealLabelArr
      })
      map.add(polygonArr);
      // 缩放地图到合适的视野级别
      map.setFitView(polygonArr)
    }
    //每个多边形添加label
    function showText(polygon) {
      var point = getCenterPoint(polygon.getPath());  //获得中心点
      var label = new AMap.Text({
        text: 'labelname',
        anchor: 'center', // 设置文本标记锚点
        style: {
          'background-color': 'transparent',
          'border-width': 0,
          'text-align': 'center',
          'font-size': '14px',
          'color': '#444444',
        },
        // offset: new AMap.Pixel(0, 0),
        position: point
      });
      label.setMap(map);
      return label;
    }
    // 获得图形的中心点
    function getCenterPoint(path) {
      var x = 0.0;
      var y = 0.0;
      for (var i = 0; i < path.length; i++) {
        x = x + parseFloat(path[i].lng);
        y = y + parseFloat(path[i].lat);
      }
      x = x / path.length;
      y = y / path.length;
      return new AMap.LngLat(x, y);
    }
    //添加多边形
    function addPolygon() {
      drawPolygon();
    }
    //绘制多边形
    function drawPolygon() {
      polyEditor.close();
      polyEditor.setTarget();
      polyEditor.open();
    }
    //开启多边形编辑
    function editPolygon() {
      initEditor(); //初始化地图编辑器
      isEdit = true;
      // polyEditor.open();
    }
    //初始化地图编辑器
    function initEditor() {
      polyEditor = new AMap.PolygonEditor(map)
      polyEditor.addAdsorbPolygons(polygonArr);
      polyEditor._opt.createOptions = { // 创建区域的样式
        fillColor: "#FF8D8D",
        fillOpacity: 0.3,
        strokeWeight: 3,
        strokeColor: "#FF8D8D",
        strokeOpacity: 1,
      };
      polyEditor._opt.editOptions = {// 编辑区域的样式
        fillColor: "#FF8D8D",
        fillOpacity: 0.3,
        strokeWeight: 3,
        strokeColor: "#FF8D8D",
        strokeOpacity: 1,
      };
      // polyEditor.midControlPoint = { // 点位样式
      //   fillColor: "#FF8D8D",
      //   fillOpacity: 1,
      //   strokeWeight: 2,
      //   strokeColor: "#FF8D8D",
      //   bubble: false,
      //   clickable: true,
      //   cursor: "pointer",
      // };
      // polyEditor.controlPoint = {// 点位样式
      //   fillOpacity: 1,
      //   strokeWeight: 2,
      //   strokeColor: "#FF8D8D",
      //   bubble: false,
      //   clickable: true,
      //   cursor: "pointer",
      // };
 
      polygonArr && polygonArr.forEach((polygon, index) => {
        //多边形添加双击事件
        polygon.on('dblclick', () => {
          if (polyEditor) {
            polyEditor.setTarget(polygon);
            polyEditor.open();
          }
        })
        //绑定右击事件——弹出右键菜单
        polygon.on('rightclick', function (e) {
          clearOne(e.lnglat, polygon, labelArr[index]); //创建右键菜单menu 删（删除多边形）
        });
        // //鼠标高亮效果
        // polygon.on('mouseover', function (e) {
        //   polygon.setOptions({
        //     fillColor: '#1791fc',
        //   })
        // });
        // polygon.on('mouseout', function (e) {
        //   polygon.setOptions({
        //     fillColor: '#FF8D8D',
        //   })
        // });
      })
 
 
      //多边形添加
      polyEditor.on('add', function (data) {
        console.log('add');
        var polygon = data.target;
        //
        polyEditor.addAdsorbPolygons(polygon);
        polygonArr.push(polygon);
        //
        var label = showText(polygon); //每个多边形添加label
        labelArr.push(label)
        // 双击图层进行编辑
        polygon.on('dblclick', () => {
          if (polyEditor) {
            polyEditor.setTarget(polygon);
            polyEditor.open();
          }
        })
        //绑定右击事件——弹出右键菜单
        polygon.on('rightclick', function (e) {
          clearOne(e.lnglat, polygon, label); //创建右键菜单menu 删（删除多边形）
        });
        // setTimeout(() => {
        //   addPolygon(); //添加多边形
        // }, 400)
      })
 
    }
    //创建右键菜单 删（删除多边形）
    function clearOne(lnglat, onePolygon, oneLabel) {
      var rightMenu = new AMap.ContextMenu();
      rightMenu.addItem('删除', function (e) {
        // if (that.isEdit) {
        removePolygon(onePolygon, oneLabel);
        rightMenu.close()
        // } else {
        //   that.$messageBlock('error', '当前未在编辑状态');
        // }
      }, 0);
      rightMenu.open(map, lnglat);
    }
    //删除某个多边形
    function removePolygon(onePolygon, oneLabel) {
      polyEditor.close(); //关闭编辑器
      map.remove(onePolygon);
      map.remove(oneLabel);
      // 获取覆盖物
      var overlays = map.getAllOverlays('polygon');
      polygonArr = overlays
    }
    //保存绘制数据
    function submitData(flag) {
      if (flag == 1) { //取消
        polyEditor.close();
        polyEditor = null;
        isEdit = false;
        map.clearMap(); // 清除地图上所有添加的覆盖物
        getInitMapData() //获取初始地图多边形数据
      } else if (flag == 2) { //保存
        console.log(polygonArr)
      }
    }
  </script>
</body>
 
</html>